<template>
    <el-container>
        <el-main>
            <avue-crud ref="multipleTable" :data="tableData" :option="tableColumns" :page="page" @refresh-change="refresh"
                @search-change="searchChange" @search-reset="searchReset" @filter-change="filterChange" @size-change="sizeChange"
                @current-change="currentChange">
                <template slot="menuLeft">
                    <el-button v-for="(item,index) in toolbar" :key="index" :type="item.type" :class="item.hide?'hide':''"
                        @click.native="btnclick(item.funName)" size="small">{{ item.label }}</el-button>
                </template>
                <template slot="menu" slot-scope="{row}">
                    <el-button size="small" type="text" class="primarybtn-color"
                        @click.native="customerViewed(row)">
                        查看
                    </el-button>
                </template>
            </avue-crud>
            <el-dialog :destroy-on-close="false" :close-on-click-modal="false" :visible.sync="cutomerVisible" :before-close="handleCloseBindCutomer"
                fullscreen>
                <avue-tabs :option="customerSetOptions" @change="customerSetHandleChange"></avue-tabs>
                <span v-if="customerTabCheck.prop === 'selectColumns'">
                    <div style="text-align: center">
                        <el-transfer style="text-align: left; display: inline-block" v-model="customerColumnValue"
                            filterable :titles="['可选字段', '已选字段']" :data="customerColumnData">
                            <el-button style="display: none;" class="transfer-footer" slot="left-footer" size="small">操作</el-button>
                            <el-button class="transfer-footer" slot="right-footer" size="small" @click="customerColumnSave(1)">保存</el-button>
                        </el-transfer>
                    </div>
                </span>
                <span v-else-if="customerTabCheck.prop === 'columnsSet'">
                    <avue-crud ref="customerColumnListCrud" :option="customerColumnListOption" :data="customerColumnList"
                        @row-update="customerColumnListUpdate" @sortable-change="customerColumnListSortableChange">
                        <template slot="menuLeft">
                            <el-button @click="customerColumnSave(2)" type="primary" size="small">排序保存</el-button>
                        </template>
                    </avue-crud>
                </span>
            </el-dialog>
        </el-main>
    </el-container>
</template>

<script>
    import {
        api
    } from "@/api/common";
    export default {
        data() {
            return {
                flowId: '',
                cutomerVisible: false,
                cutomerTitle: '',
                page: {
                    currentPage: 1,
                    total: 0,
                    pageSize: 10
                },
                searchForm: {},
                filterForm: {},
                tableData: [],
                tableColumns: {
                    border: true,
                    stripe: false,
                    showHeader: true,
                    index: false,
                    page: true,
                    align: 'left',
                    menuAlign: 'center',
                    addBtn: false,
                    delBtn: false,
                    editBtn: false,
                    menu: true,
                    columnBtn: false,
                    searchMenuSpan: 4,
                    column: [],
                },
                toolbar: [{
                    funName: 'customerExport',
                    label: '导出',
                    type: 'primary'
                }, {
                    funName: 'customerConfig',
                    label: '列表设置',
                    type: 'warning'
                }],
                customerSetOptions: {
                    column: [{
                        label: '列表字段选择',
                        prop: 'selectColumns',
                    }, {
                        label: '列表字段设置',
                        prop: 'columnsSet',
                    }]
                },
                customerTabCheck: {
                    prop: 'selectColumns'
                },
                customerColumnData: [],
                customerColumnValue: [],
                customerColumnList: [],
                customerColumnListOption: {
                    sortable: true,
                    addBtn: false,
                    editBtn: false,
                    delBtn: false,
                    addRowBtn: false,
                    cellBtn: true,
                    refreshBtn: false,
                    columnBtn: false,
                    rowKey: 'key',
                    menuWidth: 250,
                    column: [{
                        label: '原字段中文名',
                        prop: 'origin',
                        cell: false,
                    }, {
                        label: '字段名',
                        prop: 'key',
                        cell: false,
                    }, {
                        label: '字段列表别名',
                        prop: 'label',
                        cell: true,
                    }]
                },
            }
        },
        mounted() {
            const s = document.createElement('script');
            s.type = 'text/javascript';
            s.src = 'https://cdn.staticfile.org/Sortable/1.10.0-rc2/Sortable.min.js';
            document.body.appendChild(s);
        },
        watch: {
            "$route": function(to, from) {
                if (to.path != from.path) {
                    let path = this.$route.path
                    this.flowId = path.split("/")[3]
                    this.getCustomerColumnsConfig()
                    this.getTableList()
                }
            }
        },
        created() {
            let path = this.$route.path
            this.flowId = path.split("/")[3]
            this.getCustomerColumnsConfig()
            this.getTableList();
        },
        methods: {
            getCustomerColumnsConfig() {
                let params = {
                    flowId: this.flowId
                }
                let _this = this
                _this.axios.post(api.getCustomerColumnsConfig, params).then((res) => {
                    if (res.data.code == 10000) {
                        _this.tableColumns.column = res.data.data.gridColumns
                    }
                }).catch((err) => {
                    console.log('调用失败', err)
                })
            },
            // 表格刷新
            refresh() {
                this.getTableList();
            },
            // 搜索
            searchChange(params, done) {
                this.page.currentPage = 1
                this.getTableList(params)
                Object.assign(this.searchForm, params)
                done()
            },
            // 搜索清空
            searchReset() {
                this.page.currentPage = 1
                this.$set(this.searchForm, 'keyword', '')
                this.getTableList()
            },
            // 表格过滤（高级搜索）
            filterChange(result) {
                this.getTableList(result)
                this.filterForm = result
            },
            // 分页
            sizeChange(val) {
                this.page.currentPage = 1
                this.page.pageSize = val
                this.getTableList();
            },
            // 当前页
            currentChange(val) {
                this.page.currentPage = val
                this.getTableList();
            },
            // 获取表格数据
            async getTableList(where) {
                let params = {
                    flowId: this.flowId,
                    page: this.page.currentPage,
                    limit: this.page.pageSize
                }
                params = Object.assign({}, params, this.searchForm)
                params = Object.assign({}, params, this.filterForm)
                if (where) {
                    params = Object.assign({}, params, where)
                }
                let _this = this
                _this.axios.post(api.getCustomerJobList, params).then((res) => {
                    if (res.data.code == 10000) {
                        _this.tableData = res.data.data.list
                        _this.page.total = res.data.data.count
                    } else {
                        _this.tableData = []
                        _this.page.total = 0
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'error'
                        });
                    }
                }).catch((err) => {
                    _this.tableData = []
                    _this.page.total = 0
                    console.log('调用失败', err)
                })
            },
            btnclick(func) {
                this[func]()
            },
            customerExport() {
                let _this = this,
                    params = {
                        flowId: this.flowId,
                    }
                
                _this.axios.post(api.exportCustomerListByFlowId, params, {
                    responseType: 'blob'
                }).then(response => {
                    let data = response.data
                    let fileReader = new FileReader();
                    fileReader.onload = function() {
                        try {
                            let jsonData = JSON.parse(this.result);
                            _this.$message({
                                showClose: false,
                                message: jsonData.message,
                                type: 'info'
                            })
                        } catch (err) {
                            let blob = new Blob([response.data], {
                                type: 'application/vnd.ms-excel;charset=utf-8'
                            })
                            let filename = decodeURI(response.headers['content-disposition'].split('=')[1])
                                .replace(/^"*|"*$/g, '')
                            if ('download' in document.createElement('a')) { // 非IE下载
                                const elink = document.createElement('a')
                                elink.download = filename
                                elink.style.display = 'none'
                                elink.href = URL.createObjectURL(blob)
                                document.body.appendChild(elink)
                                elink.click()
                                document.body.removeChild(elink)
                                window.URL.revokeObjectURL(elink.href) //释放掉blob对象
                            } else { // IE10+下载
                                navigator.msSaveBlob(blob, filename)
                            }
                        }
                    };
                    fileReader.readAsText(data)
                }).catch((err) => {
                    console.log(err)
                    _this.$message({
                        showClose: false,
                        message: '导出失败',
                        type: 'error'
                    })
                })
            },
            customerViewed(row) {
                this.$message({
                    showClose: false,
                    message: '暂未开发',
                    type: 'info'
                })
            },
            customerConfig() {
                this.cutomerVisible = true
                this.cutomerTitle = '别表设置'
                this.getCustomerColumnsSet()
            },
            handleCloseBindCutomer() {
                this.cutomerVisible = false
                this.cutomerTitle = ''
                this.getCustomerColumnsConfig()
                this.getTableList()
            },
            customerSetHandleChange(column) {
                this.customerTabCheck = column
                this.getCustomerColumnsSet()
            },
            getCustomerColumnsSet() {
                let _this = this,
                    params = {
                        flowId: this.flowId,
                    }
                _this.axios.post(api.getCustomerColumnsSet, params).then((res) => {
                    if (res.data.code == 10000) {
                        _this.customerColumnData = res.data.data.source
                        _this.customerColumnValue = res.data.data.target
                        _this.customerColumnList = res.data.data.targetList
                    } else {
                        _this.customerColumnData = []
                        _this.customerColumnValue = []
                        _this.customerColumnList = []
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'error'
                        });
                    }
                }).catch((err) => {
                    _this.customerColumnData = []
                    _this.customerColumnValue = []
                    _this.customerColumnList = []
                    console.log('调用失败', err)
                })
            },
            customerColumnSave(type) {
                let _this = this,
                    url = api.customerColumnsSetSave,
                    params = {}
            
                params['flowId'] = _this.flowId
                params['type'] = type
                
                if (type === 1) {
                    params['target'] = _this.customerColumnValue
                } else {
                    if (_this.customerColumnList.length === 0) {
                        _this.$message({
                            showClose: false,
                            message: '无需保存的数据',
                            type: 'info'
                        });
                        return false;
                    }
                    
                    params['target'] = _this.customerColumnList
                }
                
                let _sucess_callback = function() {
                    _this.getCustomerColumnsSet()
                }
            
                _this.handleAxiosFun(url, params, _sucess_callback)
            },
            customerColumnListUpdate(form, index, done, loading) {
                let _this = this,
                    url = api.customerColumnsSetSave,
                    param = {}
                param['flowId'] = _this.flowId
                param['target'] = _this.customerColumnList
                param['type'] = 2
                loading()
                _this.axios.post(url, param).then((res) => {
                    if (res.data.code == 10000) {
                        _this.getCustomerColumnsSet()
                    } else {
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'error'
                        });
                    }
                    done()
                }).catch((err) => {
                    done()
                    console.log('调用失败', err)
                })
            },
            customerColumnListSortableChange(oldindex, newindex, row, list) {
                this.customerColumnList = []
                this.$nextTick(() => {
                    this.customerColumnList = list;
                })
            },
            // axios接口请求
            handleAxiosFun(url, params, _sucess_callback, _fail_callback) {
                let _this = this
            
                _this.axios.post(url, params).then((res) => {
                    if (res.data.code == 10000) {
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'success'
                        });
                        if (_sucess_callback && typeof _sucess_callback === 'function') {
                            _sucess_callback()
                        } else {
                            _this.getTableList()
                        }
                    } else {
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'error'
                        });
                        if (_fail_callback && typeof _fail_callback === 'function') {
                            _fail_callback()
                        }
                    }
                }).catch(() => {
                    _this.$message({
                        showClose: false,
                        message: '调用失败',
                        type: 'error'
                    });
                })
            }
        }
    }
</script>

<style lang="scss">
    .avue-crud__right {
        position: relative;
    }
    .fast-search {
        position: absolute;
        right: 218px;
    }
    .el-transfer-panel{
        height: 400px;
    }
    .el-transfer-panel__list.is-filterable{
        height: 256px;
    }
</style>
